var r = require("./trim"), t = /(\w+)\[(\d+)\]/, e = function(r) {
    try {
        return encodeURIComponent(r);
    } catch (t) {
        t = VM2_INTERNAL_STATE_DO_NOT_USE_OR_PROGRAM_WILL_FAIL.handleException(t);
        return r;
    }
}, n = function(r) {
    try {
        return decodeURIComponent(r.replace(/\+/g, " "));
    } catch (t) {
        t = VM2_INTERNAL_STATE_DO_NOT_USE_OR_PROGRAM_WILL_FAIL.handleException(t);
        return r;
    }
};

exports.parse = function(e) {
    if ("string" != typeof e) return {};
    if ("" == (e = r(e))) return {};
    "?" == e.charAt(0) && (e = e.slice(1));
    for (var i = {}, u = e.split("&"), o = 0; o < u.length; o++) {
        var c = u[o].split("="), s = n(c[0]);
        (s = t.exec(s)) ? (i[s[1]] = i[s[1]] || [], i[s[1]][s[2]] = n(c[1])) : i[c[0]] = null == c[1] ? "" : n(c[1]);
    }
    return i;
}, exports.stringify = function(r) {
    if (!r) return "";
    var t, n = [];
    for (t in r) {
        var i = r[t];
        if (Array.isArray(i)) for (var u = 0; u < i.length; ++u) n.push(e(t + "[" + u + "]") + "=" + e(i[u])); else n.push(e(t) + "=" + e(r[t]));
    }
    return n.join("&");
};